/* * * * M A P V I S I O N   L I C E N S E  *****************************************************************
 *
 * This MapVision software is © Filip Zavadil 2013. It is licensed under the LGPL license.
 * This MapVision software dynamically links to unmodified Qt5 Library.
 *
 * The Qt5 Library is © 2013 Qt® and/or its subsidiary(-ies), and is licensed under the
 * GNU Lesser General Public License version 2.1 with Qt® LGPL exception version 1.1.
 * Qt5 library is free software; you can redistribute it and/or modify it under the terms of the
 * GNU Lesser General Public License, version 2.1, as published by the Free Software Foundation.
 * Qt5 library is provided “AS IS”, without WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
 *
 * As an additional permission to the GNU Lesser General Public License version 2.1, the object
 * code form of a “work that uses the Library” may incorporate material from a header file that is
 * part of the Library. You may distribute such object code under terms of your choice,
 * provided that: (i) the header files of the Library have not been modified; and (ii)
 * the incorporated material is limited to numerical parameters, data structure layouts, accessors,
 * macros, inline functions and templates; and (iii) you comply with the terms of Section 6 of the
 * GNU Lesser General Public License version 2.1.
 *
 * Moreover, you may apply this exception to a modified version of the Library, provided that such
 * modification does not involve copying material from the Library into the modified Library’s header
 * files unless such material is limited to (i) numerical parameters; (ii) data structure layouts;
 * (iii) accessors; and (iv) small macros, templates and inline functions of five lines or less in length.
 *
 * Furthermore, you are not required to apply this additional permission to a modified version of the Library.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this package;
 * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

 * The source code for Qt 5.X SDK is available from Qt Project here:
 * http://download.qt-project.org/official_releases/qtcreator/2.7/2.7.0/qt-creator-2.7.0-src.zip.
 *
 * ****************************** M A P V I S I O N    S O F T W A R E  ************************************
 *
 * Author:       Filip Zavadil
 * Description:  Software for displaying and exporting map tiles.
 * The sources and executables of MapVision software are available:
 *    - from project hosting on CodePlex.com :   http://mapvision.codeplex.com
 *    - from GIT repositories on Gitorious.org:  https://gitorious.org/mapvision
 * Visit MapVision fanpage on Facebook.com:      https://www.facebook.com/pages/Mapvision/631827753513935
 *
 * *********************************************************************************************************
*/

#include "dialoglayertileslocal.h"
#include "ui_dialoglayertileslocal.h"

DialogLayerTILESlocal::DialogLayerTILESlocal(QWidget *parent, Layer * layer_) :
    QDialog(parent), ui(new Ui::DialogLayerTILESlocal), layer(layer_)
{
    ui->setupUi(this);
    this->setWindowIcon(QIcon("images/buttons/addTilesLocal.svg"));
    this->setWindowTitle(tr("Add local TMS/WMTS layer"));
}

DialogLayerTILESlocal::~DialogLayerTILESlocal()
{
    delete ui;
}

void DialogLayerTILESlocal::on_pushButtonOpen_clicked()
{
    QString path=layer->settings.value("layer/TILESlocal").toString();
    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
                                                    path,
                                                    QFileDialog::ShowDirsOnly
                                                    | QFileDialog::DontResolveSymlinks);

    QDir dir2(dir);

    if (dir2.isReadable() && dir != "")
    {
        ui->sourcePath->setText(dir2.path());
        this->setOrigin(dir2);
        layer->settings.setValue("layer/TILESlocal",dir2.path());
        ui->layerName->setText(dir2.path().mid(dir2.path().lastIndexOf("/")+1,-1));
    }
    else
    {
        emit layer->sendMessagePublic("<span style=\"color: #680000;\">"+ tr(" it is not selected a directory")+ "</span>");
    }
}

void DialogLayerTILESlocal::setOrigin(QDir source)
{
    QList<int> zooms,Xs,Ys;



    bool ok;

    QStringList zoomsList =source.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Readable);
    if (zoomsList.count()==0)
    {
        QMessageBox msgBox;
                    msgBox.setText(tr("This is not valid Tile Map Service file structure!"));
                    msgBox.exec();
                    ui->sourcePath->setText("");
                    return;
    }

    foreach (QString zoom,zoomsList ) {
        zooms << zoom.toInt(&ok);
        if (!ok)
        {
            QMessageBox msgBox;
            msgBox.setText(tr("This is not valid Tile Map Service file structure!"));
            msgBox.exec();
            ui->sourcePath->setText("");
            return;
        }
    }

    qSort(zooms.begin(),zooms.end());

    ui->spinBoxOriginZoom->setValue(zooms[0]);


    source.setPath(source.path()+"/"+QString::number(zooms[0]));

    QStringList XsString =source.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Readable);

    if (XsString.count()==0)
    {
        QMessageBox msgBox;
        msgBox.setText(tr("This is not valid Tile Map Service file structure!"));
        msgBox.exec();
        ui->sourcePath->setText("");
        return;

    }

    foreach (QString x,XsString ) {
        Xs << x.toInt(&ok);
        if (!ok)
        {
            QMessageBox msgBox;
            msgBox.setText(tr("This is not valid Tile Map Service file structure!"));
            msgBox.exec();
            ui->sourcePath->setText("");
            return;
        }
    }


    qSort(Xs.begin(),Xs.end());

   int Xmean = Xs[double(Xs.size())/double(2)];

    source.setPath(source.path()+"/"+QString::number(Xmean));

     foreach (QString y, source.entryList(QDir::Files)) {

        y=y.remove(".png");
        Ys << y.toInt(&ok);
        if (!ok) {
            QMessageBox msgBox;
            msgBox.setText(tr("This is not valid Tile Map Service file structure!"));
            msgBox.exec();
            ui->sourcePath->setText("");
            return;
        }
    }

    int Ymean = Ys[double(Ys.size())/double(2)];

    QPointF lonlat = layer->zavaProj.tileFormat2lonlat(QPoint(Xmean,Ymean),zooms[0],ZavaProj::BOTTOM);

    QString lonlatString = layer->zavaProj.lonlat2dms(lonlat);

    ui->lineEditOriginWGS->setText(lonlatString);

}


void DialogLayerTILESlocal::on_pushButtonAccepted_clicked()
{
    if (ui->sourcePath->text() == "")
    {
        QMessageBox msgBox;
        msgBox.setText(tr("Source cannot be empty"));
        msgBox.exec();
        on_pushButtonOpen_clicked();
    }
    else if (ui->layerName->text().remove(" ") == "")
    {
        QMessageBox msgBox;
        msgBox.setText(tr("LayerName cannot be empty"));
        msgBox.exec();
    }
    else
    {
        this->accept();
        layer->setLayerName(ui->layerName->text());
        layer->setSource(ui->sourcePath->text());
        layer->getMapView()->setZoom(ui->spinBoxOriginZoom->value());
        layer->getMapView()->setCenterLonLat(ui->lineEditOriginWGS->text());
        layer->setOrigin(layer->getMapView()->getCenterLonLat(),layer->getMapView()->getZoom());
        if (ui->radioButtonYaxisOriginBottom->isChecked())
        {
            layer->setLayerType(Layer::TMSlocal);
            layer->YaxisOrigin = ZavaProj::BOTTOM;
        }
        else
        {
            layer->setLayerType(Layer::WMTSlocal);
            layer->YaxisOrigin = ZavaProj::TOP;
        }
    }
}

void DialogLayerTILESlocal::on_pushButtonReject_clicked()
{
    this->reject();
}

void DialogLayerTILESlocal::on_pushButtonUseCurrentOrigin_clicked()
{
     ui->lineEditOriginWGS->setText(layer->zavaProj.lonlat2dms(layer->getMapView()->getCenterLonLat()));
     ui->spinBoxOriginZoom->setValue(layer->getMapView()->getZoom());
}
